package com.tools.payhelper;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.tools.payhelper.nxes.ConnectBean;
import com.tools.payhelper.nxes.LoginBean;
import com.tools.payhelper.nxes.NxOrder;
import com.tools.payhelper.nxes.PayInfo;
import com.tools.payhelper.nxes.QrCode;
import com.tools.payhelper.utils.AbSharedUtil;
import com.tools.payhelper.utils.DBManager;
import com.tools.payhelper.utils.JSONParser;
import com.tools.payhelper.utils.LogUtil;
import com.tools.payhelper.utils.MD5;
import com.tools.payhelper.utils.PayHelperUtils;
import com.tools.payhelper.utils.QrCodeBean;
import com.tools.payhelper.ws.WsManager;
import com.tools.payhelper.ws.WsStatusListener;

import org.json.JSONObject;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okio.ByteString;

import static com.tools.payhelper.AlipayHook.HONGBAO_ACTION;
import static com.tools.payhelper.utils.PayHelperUtils.NEWMARK_ACTION;


public class MainActivity extends Activity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {

    public static TextView console;
    private static ScrollView scrollView;
    private BillReceived billReceived;
    private AlarmReceiver alarmReceiver;
    public static String BILLRECEIVED_ACTION = "com.tools.payhelper.billreceived";
    public static String QRCODERECEIVED_ACTION = "com.tools.payhelper.qrcodereceived";
    public static String MSGRECEIVED_ACTION = "com.tools.payhelper.msgreceived";
    public static String TRADENORECEIVED_ACTION = "com.tools.payhelper.tradenoreceived";
    public static String LOGINIDRECEIVED_ACTION = "com.tools.payhelper.loginidreceived";
    public static String NOTIFY_ACTION = "com.tools.payhelper.notify";
    public static String SAVEALIPAYCOOKIE_ACTION = "com.tools.payhelper.savealipaycookie";
    public static String XINGE_ACTION = "com.tools.payhelper.xinge.push.action";
    public static String XINGE_ACTION_LOGOUT = "com.tools.payhelper.xinge.push.action.logout";
    public static String NX_GET_BILL = "com.tools.payhelper.nx.getbill";

    public static String TCPSTATUS_ACTION = "com.tools.payhelper.tcpstatus";
    public static String UPDATEBALANCE_ACTION = "com.tools.payhelper.updatebalance";
    public static final String ACTION_NOTIFI = "com.chuxin.socket.ACTION_NOTIFI";


    EditText et_ws;
    Button kq_btn, unpay, JY;
    public static String unpayDate = "";
    private DBManager dbManager;
    private WsManager wsManager;
    private Context mContext;
    private Button btnServer;
    private TextView txt_id, txt_key;
    private FlowableEmitter flowableEmitter;
    private Subscription mSubscription;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        try {
            setContentView(R.layout.activity_main);
            mContext = this;
            initView();
            initMain();
            dbManager = new DBManager(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        txt_id = (TextView) findViewById(R.id.txt_id);
        txt_key = (TextView) findViewById(R.id.txt_key);
        String userId = AbSharedUtil.getString(mContext, "userId");
        String applyId = AbSharedUtil.getString(mContext, "applyId");
        if(!TextUtils.isEmpty(userId)){
            txt_id.setText("商户ID：" + userId);
        }
        if(!TextUtils.isEmpty(applyId)){
            txt_key.setText("应用ID：" + applyId);
        }
    }

    private void initMain() {

        console = (TextView) findViewById(R.id.console);
        scrollView = (ScrollView) findViewById(R.id.scrollview);
        //注册广播
        billReceived = new BillReceived();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BILLRECEIVED_ACTION);
        intentFilter.addAction(PayHelperUtils.LOGING_ACTION);
        intentFilter.addAction(PayHelperUtils.LOGOUT_ACTION);
        intentFilter.addAction(MSGRECEIVED_ACTION);
        intentFilter.addAction(QRCODERECEIVED_ACTION);
        intentFilter.addAction(TRADENORECEIVED_ACTION);
        intentFilter.addAction(LOGINIDRECEIVED_ACTION);
        intentFilter.addAction(NEWMARK_ACTION);
        intentFilter.addAction(ACTION_NOTIFI);
        intentFilter.addAction(SAVEALIPAYCOOKIE_ACTION);
        intentFilter.addAction(XINGE_ACTION);
        intentFilter.addAction(XINGE_ACTION_LOGOUT);
        intentFilter.addAction(NX_GET_BILL);

        intentFilter.addAction(TCPSTATUS_ACTION);
        intentFilter.addAction(UPDATEBALANCE_ACTION);
        intentFilter.addAction(HONGBAO_ACTION);
        intentFilter.addAction("com.payhelper.success.response");

        registerReceiver(billReceived, intentFilter);

        alarmReceiver = new AlarmReceiver();
        IntentFilter alarmIntentFilter = new IntentFilter();
        alarmIntentFilter.addAction(NOTIFY_ACTION);
        registerReceiver(alarmReceiver, alarmIntentFilter);

        startService(new Intent(this, DaemonService.class));

//		PayHelperUtils.queryDingDingOrder(this);

        sendmsg("当前软件版本:" + PayHelperUtils.getVerName(getApplicationContext()));
        initQRCodeQueue();
    }


    /**
     * 连接WS
     */
    private void connectToWsServer() {
        String wsUrl = AbSharedUtil.getString(mContext, "wsurl");
        String data = AbSharedUtil.getString(mContext, "data");
        if(TextUtils.isEmpty(wsUrl) || TextUtils.isEmpty(data) ){
            Toast.makeText(getApplicationContext(), "未检测到数据,请先进行配置!", Toast.LENGTH_LONG).show();
            return;
        }

        if (wsManager != null) {
            wsManager.stopConnect();
            wsManager = null;
        }

        wsManager = new WsManager.Builder(getBaseContext()).client(
                new OkHttpClient().newBuilder()
                        .pingInterval(15, TimeUnit.SECONDS)
                        .retryOnConnectionFailure(true)
                        .build())
                .needReconnect(true)
                .wsUrl(wsUrl)
                .build();
        wsManager.setWsStatusListener(wsStatusListener);
        wsManager.startConnect();
    }


    /**
     * WS回调
     */
    private WsStatusListener wsStatusListener = new WsStatusListener() {
        @Override
        public void onOpen(okhttp3.Response response) {
            String userId = AbSharedUtil.getString(mContext, "userId");
            String applyId = AbSharedUtil.getString(mContext, "applyId");
            String key = AbSharedUtil.getString(mContext, "key");
            String action = "login";
            String sign =MD5.md5(userId + applyId + action + key);
            LoginBean bean = new LoginBean(userId, applyId,action,sign);
            String msg = JSONParser.toString(bean);
            wsManager.sendMessage(msg);
            sendmsg("WS服务器连接成功");
            btnServer.setText("停止服务");
        }

        @Override
        public void onMessage(String text) {
            sendmsg("WS信息:" + text);
            LogUtil.printLog("WS-----收到指令" + text);
            if (TextUtils.isEmpty(text)) {
                return;
            }

            //收到WS消息 去产码 消息格式为 {"money":"0.01"}
            PayInfo pay = (PayInfo) JSONParser.toObject(text, PayInfo.class);
            if (pay != null) {
                //加入队列
                flowableEmitter.onNext(pay);
            }
        }

        @Override
        public void onMessage(ByteString bytes) {
            LogUtil.printLog("WS-----收到指令");
        }

        @Override
        public void onReconnect() {
            sendmsg("WS服务器重连中.");
            LogUtil.printLog("WS-----服务器重连中.");
        }

        @Override
        public void onClosing(int code, String reason) {
            LogUtil.printLog("WS-----服务器关闭中.");
        }

        @Override
        public void onClosed(int code, String reason) {
            LogUtil.printLog("WS-----服务器已关闭.");
            sendmsg("WS服务器已关闭.");
            btnServer.setText("启动服务");
        }

        @Override
        public void onFailure(Throwable t, okhttp3.Response response) {
            LogUtil.printLog("WS-----服务器连接失败");
            sendmsg("WS服务器连接失败.");
            btnServer.setText("启动服务");
        }
    };

    private void sendWsMsg(String msg) {
        if (wsManager != null && wsManager.isWsConnected()) {
            wsManager.sendMessage(msg);
        } else {
            sendmsg("ws已断开,发送消息失败");
        }
    }


    private void initData(String info) {
    }


    private void initView() {

/*        kq_btn = (Button) findViewById(R.id.kq_btn);
        kq_btn.setOnClickListener(this);*/
        unpay = (Button) findViewById(R.id.unpay);
        JY = (Button) findViewById(R.id.JY);
        unpay.setOnClickListener(this);
        et_ws = (EditText) findViewById(R.id.et_ws);
        JY.setOnClickListener(this);
        btnServer = (Button) findViewById(R.id.btn_server);

        btnServer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (wsManager != null) {
                    if (wsManager.isWsConnected()) {
                        wsManager.stopConnect();
                    } else {
                        connectToWsServer();
                    }
                } else {
                    connectToWsServer();
                }
            }
        });
    }


    public static Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            try {
                String txt = msg.getData().getString("log");
                if (console != null) {
                    if (console.getText() != null) {
                        if (console.getText().toString().length() > 7500) {
                            console.setText("日志定时清理完成..." + "\n\n" + txt);
                        } else {
                            console.setText(console.getText().toString() + "\n\n" + txt);
                        }
                    } else {
                        console.setText(txt);
                    }
                    scrollView.post(new Runnable() {
                        public void run() {
                            scrollView.fullScroll(View.FOCUS_DOWN);
                        }
                    });
                }
                super.handleMessage(msg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    };

    @Override
    protected void onDestroy() {
        try {
            unregisterReceiver(alarmReceiver);
            unregisterReceiver(billReceived);

            if (mSubscription != null) {
                mSubscription.cancel();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        String userId = AbSharedUtil.getString(mContext, "userId");
        String applyId = AbSharedUtil.getString(mContext, "applyId");
        if(!TextUtils.isEmpty(userId)){
            txt_id.setText("商户ID：" + userId);
        }
        if(!TextUtils.isEmpty(applyId)){
            txt_key.setText("应用ID：" + applyId);
        }

    }
    public static void sendmsg(String txt) {
        try {
            Log.i("HHH", txt);
            Message msg = new Message();
            msg.what = 1;
            Bundle data = new Bundle();
            long l = System.currentTimeMillis();
            Date date = new Date(l);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String d = dateFormat.format(date);
            data.putString("log", d + ":" + " " + txt);
            msg.setData(data);

            handler.sendMessage(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 过滤按键动作
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_update:
                break;
            case R.id.ll_setting:
                Intent intent = new Intent(MainActivity.this, SettingActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_about:
                Intent intentabout = new Intent();
                intentabout.setAction("android.intent.action.VIEW");
                intentabout.setData(Uri.parse("https://www.baidu.com"));
                startActivity(intentabout);

                break;
      /*      case R.id.kq_btn:

                Intent nx = new Intent();
                nx.setAction("com.payhelper.nongxingyisao.start");
                nx.putExtra("type", "wechat");
                nx.putExtra("apiorder_id", "66666666");
                nx.putExtra("money", "0.69");
                sendBroadcast(nx);
                break;*/
            case R.id.unpay:

                Intent unIntent = new Intent("com.chuxin.socket.ACTION_CONNECT");
                unIntent.putExtra("money", "0.1");
                unIntent.putExtra("mark", "unpayMark001");
                sendBroadcast(unIntent);
                unpayDate = "";
                break;
            case R.id.JY:
                Intent intent1 = new Intent(MainActivity.this, SettingActivity.class);
                startActivity(intent1);
                break;
            case R.id.btn_exit:

                break;
        }

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.tb_ali:
                if (isChecked) {
                    AbSharedUtil.putBoolean(this, "checkqq", true);
                    return;
                } else {
                    AbSharedUtil.putBoolean(this, "checkqq", false);
                    return;
                }
            default:
                return;
        }
    }


    //自定义接受订单通知广播
    class BillReceived extends BroadcastReceiver {
        String status;
        private String money;
        private String mark;
        private String type;

        @Override
        public void onReceive(final Context context, Intent intent) {
            try {
                sendmsg("action:" +intent.getAction());
                if (intent.getAction().contentEquals(QRCODERECEIVED_ACTION)) {
                    String money = intent.getStringExtra("money");
                    String mark = intent.getStringExtra("apiorder_id");
                    String type = intent.getStringExtra("type");
                    String payurl = intent.getStringExtra("payurl");
                    DBManager dbManager = new DBManager(CustomApplcation.getInstance().getApplicationContext());
                    String dt = System.currentTimeMillis() + "";
                    DecimalFormat df = new DecimalFormat("0.00");
                    money = df.format(Double.parseDouble(money));
                    dbManager.addQrCode(new QrCodeBean(money, mark, type, payurl, dt));

                    sendmsg("生成成功,金额:" + money + "备注:" + mark + "二维码:" + payurl);

                    LogUtil.printLog("生成成功---->" + payurl);

                   // String deviceId = AbSharedUtil.getString(mContext,"no");

                    if (type.equals("nxes")) {
                        QrCode qrCode = new QrCode("4","createQrcode",payurl, mark);
                        //PayInfo bean = new PayInfo(money, payurl, deviceId);
                        //回传二维码数据
                        sendWsMsg(JSONParser.toString(qrCode));
                        sendmsg("回传二维码数据" + JSONParser.toString(qrCode));

                        //回传二维码数据后,从队列拿出下一条
                        mSubscription.request(1);

                        PayHelperUtils.startAPP();
                        return;
                    }

                    PayHelperUtils.startAPP();

                } else if (intent.getAction().contentEquals(MSGRECEIVED_ACTION)) {
                    String msg = intent.getStringExtra("msg");
                    sendmsg(msg);
                } else if (intent.getAction().contentEquals(SAVEALIPAYCOOKIE_ACTION)) {
                    String cookie = intent.getStringExtra("alipaycookie");
                    PayHelperUtils.updateAlipayCookie(MainActivity.this, cookie);
                } else if (intent.getAction().contentEquals(LOGINIDRECEIVED_ACTION)) {
                    String loginid = intent.getStringExtra("loginid");
                    String type = intent.getStringExtra("type");
                    if (!TextUtils.isEmpty(loginid)) {
                        if (type.equals("nxys")) {
                            LogUtil.printLog("获取广播.启动轮训");
                            PayHelperUtils.startAlipayMonitor(context);
                        }
                    }
                } else if ("com.payhelper.success.response".equals(intent.getAction())) {
                    String response = intent.getStringExtra("response");
                    String apiOrderNo = intent.getStringExtra("apiOrderNo");
                    AbSharedUtil.putString(MainActivity.this, "loginData", response);
                    initData(response);
                    DBManager dbManager = new DBManager(CustomApplcation.getInstance().getApplicationContext());
                    dbManager.deleteOrderById(apiOrderNo);
                    try {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                PayHelperUtils.startAPP();
                            }
                        }, 3000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } else if (NX_GET_BILL.equals(intent.getAction())) {

                    String lis = intent.getStringExtra("list");
                    LogUtil.printLog(lis);
                    sendmsg("lis列表:" + lis);
                    List<NxOrder> nxList = (List<NxOrder>) JSONParser.toObject(lis, new TypeToken<List<NxOrder>>() {
                    }.getType());
                    if (nxList != null && nxList.size() > 0) {
                        for (NxOrder bean : nxList) {
                            if (!dbManager.isNotifyTradeNo(bean.getOrderId())) {
                                dbManager.addTradeNo(bean.getOrderId(), "0");
                                //发起通知
                                LogUtil.printLog("发起通知" + bean.getOrderId());

                                sendmsg("收到农信订单:" + bean.getOrderId() + "\n金额:" + bean.getAmount() + "\n时间:" + bean.getOrderTime());
                                notifyapi(bean.getOrderId(), bean.getAmount(), bean.getOrderTime());
                            }
                        }
                    }
                }

            } catch (Exception e) {
                PayHelperUtils.sendmsg(context, "BillReceived异常" + e.getMessage());
            }
        }

        public void notifyapi(final String orderNo, String money, String orderTime) {

            try {
                String url = AbSharedUtil.getString(mContext, "url");
                final String userId = AbSharedUtil.getString(mContext, "userId");
                final String applyId = AbSharedUtil.getString(mContext, "applyId");
                final String key = AbSharedUtil.getString(mContext, "key");
                final String t = String.valueOf(new Date().getTime());
                final String sign = MD5.md5(userId + applyId + "4" + money + orderNo + t + key);
           /*

                String uid = AbSharedUtil.getString(mContext, "no");
                String signKey = AbSharedUtil.getString(mContext, "key");
                String url = AbSharedUtil.getString(mContext, "url");*/

                HttpUtils httpUtils = new HttpUtils(15000);

              //  String sign = MD5.md5(orderNo + money + orderTime + signKey);
                RequestParams params = new RequestParams();
                params.addBodyParameter("userId", userId);//应用id
                params.addBodyParameter("applyId", applyId);//应用id
                params.addBodyParameter("type", "4");//类型
                params.addBodyParameter("orderId", orderNo);//流水号
                params.addBodyParameter("price", money);  //金额
                params.addBodyParameter("t", t);//时间戳
                params.addBodyParameter("sign",sign);//sign

                httpUtils.send(HttpMethod.POST, url, params, new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        sendmsg("发送异步通知异常，服务器异常" + arg1);
                        dbManager.updateTradeNo(orderNo, "1");
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        String result = arg0.result;
                        if (result.contains("success")) {
                            sendmsg("发送异步通知成功，服务器返回" + result);
                            dbManager.updateTradeNo(orderNo, "1");
                        } else {
                            sendmsg("发送异步通知失败，服务器返回" + result);
                            dbManager.updateTradeNo(orderNo, "1");
                        }
                    }
                });
            } catch (Exception e) {
                sendmsg("notifyapi异常" + e.getMessage());
            }
        }
    }


    /**
     * 初始化生成二维码队列
     */
    private void initQRCodeQueue() {
        Flowable.create(new FlowableOnSubscribe<PayInfo>() {
            @Override
            public void subscribe(FlowableEmitter<PayInfo> emitter) throws Exception {
                flowableEmitter = emitter;
            }
        }, BackpressureStrategy.ERROR).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<PayInfo>() {

                    @Override
                    public void onSubscribe(Subscription s) {
                        mSubscription = s;
                        s.request(1);
                    }

                    @Override
                    public void onNext(PayInfo bean) {
                        if (bean != null) {
                            Intent nx = new Intent();
                            nx.setAction("com.payhelper.nongxingyisao.start");
                            nx.putExtra("apiorder_id", bean.getOrderId());
                            nx.putExtra("money", bean.getPrice());
                            sendBroadcast(nx);
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }
}
